package objectpool

import (
	"container/list"
	"reflect"
	"sync"
)


// 初始化一批对象， 当被剩余对象为0时 ，自动再一次性初始化 一批
type ObjectPool struct {
   objects *list.List
   typ reflect.Type
   maxSize int
   mux *sync.Mutex
}

// p 类型
func NewObjectPool(p reflect.Type,max_count int) *ObjectPool {
	pool:=&ObjectPool{objects:list.New(),typ:p,maxSize:max_count}
	pool.mux = &sync.Mutex{}
	pool.initObject(max_count)
	return pool
}

// 生成对象
func (this *ObjectPool) initObject(num int) {
	now_len:=this.objects.Len()
	diff:=num - now_len
	if diff>0{
		for i:=0;i<diff;i++{
			v:=reflect.Zero(this.typ)
			o:=v.Interface()
			this.objects.PushBack(o)
		}
	}

}

// 获取对象
func (this *ObjectPool) Get() interface{} {
	now_len:=this.objects.Len()
	if now_len ==0{
		this.initObject(this.maxSize)
	}
	 e:=this.objects.Front()
	 this.objects.Remove(e)
	 return e.Value
}


// 获取加锁,速度有影响，适合多个线程获取对象
// 如果同时只有一个线程，使用Get()方法
func (this *ObjectPool) GetSafe() interface{}  {
	this.mux.Lock()
	defer this.mux.Unlock()
	now_len:=this.objects.Len()
	if now_len ==0{
		this.initObject(this.maxSize)
	}
	e:=this.objects.Front()
	this.objects.Remove(e)
	return e.Value
}
